package com.qf.realm;

import com.qf.pojo.SysUsers;
import com.qf.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 *
 *
 * @author 千峰教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    SysUserService userService;


    //提供授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SysUsers user = (SysUsers) principals.getPrimaryPrincipal();

        //获取 角色字符串信息
        Set<String> roles = userService.findRolesByUserId(user.getId());
        //获取 权限字符串信息
        Set<String> perms = userService.findPermsByUserId(user.getId());

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        // 设置角色字符串信息
        authorizationInfo.setRoles(roles);
        //设置权限字符串信息
        authorizationInfo.setStringPermissions(perms);


        return authorizationInfo;
    }


    /**
     * 提供认证信息
     *  从数据库中获取认证信息，并返回
     * @param token
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户输入的账号和密码
        String username = (String) token.getPrincipal();
        String password = new String((char[])token.getCredentials());
        //根据用户名从数据库获取用户信息
        SysUsers user = userService.findByUsername(username);

        //如果没有查询到，说明用户名未注册
        if(user == null){
            throw new UnknownAccountException("账号未注册");
        }

        //对原文密码加密
        Md5Hash md5 = new Md5Hash(password, username, 1024);

        if( ! user.getPassword().equalsIgnoreCase(md5.toString())){
            throw new IncorrectCredentialsException("密码错误");
        }

        if(user.getStatus() == 0){
            throw new LockedAccountException("账号已锁定");
        }

        /**
         * 参数1: 用户数据
         * 参数2： 密码
         * 参数3： 自定义的名称
         */
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, password,  user.getRealname() );

        return authenticationInfo;
    }
}
